<template>
  <div class="search">
    <input type="text" v-model="searchVal" placeholder="输入城市名或拼音" class="search-input">
    <div class="search-content" v-show="searchVal" ref="wrapper">
      <ul>
        <li class="search-item border-bottom" v-for="item in searchResList" :key="item.id" @click="changeCity(item.name)">
          {{item.name}}
        </li>
      </ul>
      <div v-show="hasResult">没有找到匹配数据</div>
    </div>
  </div>
</template>
<script>
import BScroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data: function () {
    return {
      searchVal: '',
      searchResList: [],
      timer: null
    }
  },
  methods: {
    changeCity: function (city) {
      this.$store.commit('changeCity', city)
      this.searchVal = ''
      this.$router.push('/')
    }
  },
  watch: {
    searchVal () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.searchVal) {
        this.searchResList = []
        return
      }
      this.timer = setTimeout(() => {
        this.searchResList = []
        for (let key in this.cities) {
          this.cities[key].forEach((item, index) => {
            if (item.name.indexOf(this.searchVal) > -1 || item.spell.indexOf(this.searchVal) > -1) {
              this.searchResList.push(item)
            }
          })
        }
      }, 16)
    }
  },
  computed: {
    hasResult () {
      return !this.searchResList.length
    }
  },
  mounted () {
    console.log(this.$refs.wrapper)
    this.scroll = new BScroll(this.$refs.wrapper)
  }
}
</script>
<style lang="stylus" scoped>
  @import '~stylus/varibles.styl'
  .search
    height: .72rem
    padding: 0 .1rem
    background: $bgColor
    .search-input
      box-sizing: border-box
      width: 100%
      height: .62rem
      padding: 0 .1rem
      line-height: .62rem
      text-align: center
      border-radius: .06rem
      color: #666
  .search-content
    z-index: 1
    overflow: hidden
    position: absolute
    top: 1.58rem
    left: 0
    right: 0
    bottom: 0
    background: #eee
    .search-item
      line-height: .62rem
      padding-left: .2rem
      background: #fff
      color: #666
</style>
